package com.seh.contentcenter.service.Impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seh.contentcenter.dto.GoodsDTO;
import com.seh.contentcenter.dto.UserDTO;
import com.seh.contentcenter.entity.Goods;
import com.seh.contentcenter.feignclient.UserCenterFeignClient;
import com.seh.contentcenter.mapper.GoodsMapper;
import com.seh.contentcenter.service.GoodsService;
import com.seh.contentcenter.utils.DTOUtil;
import com.seh.contentcenter.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RedisTemplate<String, Object> objectRedisTemplate;

    @Autowired
    private UserCenterFeignClient userCenterFeignClient;

    private static Integer pageSize = 8;

    /**
     * 查看所有商品信息
     *
     * @param pageIndex 分页索引
     * @return 商品信息列表
     */
    @Cacheable(value = "goods", key = "#pageIndex")
    @Override
    public List<GoodsDTO> findAll(Integer pageIndex) {
        // 检查缓存中是否存在指定页码的商品信息
        Boolean hasKey = objectRedisTemplate.opsForHash().hasKey("goods", pageIndex.toString());
        List<GoodsDTO> goodsDTOList = new ArrayList<>();

        if (hasKey) {
            // 从缓存中获取已缓存的结果
            List<Goods> records = JSONObject.parseArray(objectRedisTemplate.opsForHash().get("goods", pageIndex.toString()).toString(), Goods.class);

            // 遍历缓存结果，转换为DTO对象并获取用户信息
            records.forEach(f -> {
                // 转换商品信息为DTO对象
                GoodsDTO goodsDTO = DTOUtil.convertGoods(f);
                // 从缓存中直接获取用户信息（此处可能需要判断，缓存中是否存在用户信息）
                UserDTO userInfoById = UserUtil.getUserDTOFromCache(f.getUserId(), objectRedisTemplate, userCenterFeignClient);
                goodsDTO.setUserDTO(userInfoById);
                goodsDTOList.add(goodsDTO);
            });
        } else {
            // 从数据库获取数据
            Page<Goods> page = new Page<>(pageIndex, pageSize);
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_status", 0).orderByDesc("goods_id");
            page = goodsMapper.selectPage(page, queryWrapper);
            List<Goods> records = page.getRecords();

            // 遍历数据库结果，转换为DTO对象并获取用户信息
            records.forEach(f -> {
                // 转换商品信息为DTO对象
                GoodsDTO goodsDTO = DTOUtil.convertGoods(f);
                // 调用Feign客户端从用户中心获取用户信息
                UserDTO userInfoById = userCenterFeignClient.findUserInfoById(f.getUserId());
                goodsDTO.setUserDTO(userInfoById);
                goodsDTOList.add(goodsDTO);
            });

            // 将结果缓存到Redis
            objectRedisTemplate.opsForHash().put("goods", pageIndex.toString(), JSONUtil.toJsonStr(records));
        }

        return goodsDTOList;
    }

    /**
     * 模糊查询商品信息
     *
     * @param keyword 关键字
     * @return 商品信息列表
     */
    @Cacheable(value = "goods", key = "#keyword")
    @Override
    public List<Goods> findByName(String keyword) {
        // 检查缓存中是否存在数据
        Boolean hasKey = objectRedisTemplate.opsForHash().hasKey("goods", keyword);

        if (hasKey) {
            // 从缓存中获取数据
            List<Goods> records = JSONObject.parseArray(objectRedisTemplate.opsForHash().get("goods", keyword).toString(), Goods.class);
            return records;
        } else {
            // 在数据库中进行模糊查询
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("goods_name", keyword).or().like("goods_desc", keyword).or().like("goods_category", keyword);
            Page<Goods> page = new Page<>(1, 20);
            page = goodsMapper.selectPage(page, queryWrapper);
            List<Goods> records = page.getRecords();

            // 将查询到的结果存入缓存中
            objectRedisTemplate.opsForHash().put("goods", keyword, JSONUtil.toJsonStr(records));
            return records;
        }
    }

    /**
     * 根据id查询商品详细信息
     *
     * @param id 商品id
     * @return 商品详细信息DTO
     */
    @Cacheable(value = "goods", key = "#id")
    @Override
    public GoodsDTO findById(Integer id) {
        // 检查缓存中是否存在数据
        Boolean hasKey = objectRedisTemplate.opsForHash().hasKey("goods", id.toString());

        if (hasKey) {
            // 从缓存中获取数据
            Goods goods = JSONObject.parseObject(objectRedisTemplate.opsForHash().get("goods", id.toString()).toString(), Goods.class);
            GoodsDTO goodsDTO = DTOUtil.convertGoods(goods);
            return goodsDTO;
        } else {
            // 从数据库中查询商品信息
            Goods goods = goodsMapper.selectById(id);
            if (goods != null) {
                GoodsDTO goodsDTO = DTOUtil.convertGoods(goods);
                objectRedisTemplate.opsForHash().put("goods", id.toString(), JSONUtil.toJsonStr(goods));
                return goodsDTO;
            } else {
                return null;
            }
        }
    }

    /**
     * 添加新的商品信息
     *
     * @param goods
     * @return
     */
    @Override
    public String addNewGoods(Goods goods) {
        int insert = goodsMapper.insert(goods);
        if (insert > 0) {
            // 删除对应的缓存条目
            objectRedisTemplate.delete("goods");
            return "添加成功";
        }
        return "添加失败";
    }

    /**
     * 删除某一商品
     *
     * @param id
     */
    @Override
    public void deleteGoods(Integer id) {
        goodsMapper.deleteById(id);
    }

    /**
     * 根据用户id，查询该用户发布的二手商品
     *
     * @param userId     用户id
     * @param pageIndex  分页索引
     * @return 用户发布的二手商品列表
     */
    @Cacheable(value = "goods", key = "#userId + '-' + #pageIndex")
    @Override
    public List<GoodsDTO> findAllGoodsByUserId(Integer userId, Integer pageIndex) {
        // 检查缓存中是否存在数据
        String cacheKey = userId + "-" + pageIndex;
        Boolean hasKey = objectRedisTemplate.opsForHash().hasKey("goods", cacheKey);

        if (hasKey) {
            // 从缓存中获取数据
            List<Goods> records = JSONObject.parseArray(objectRedisTemplate.opsForHash().get("goods", cacheKey).toString(), Goods.class);
            List<GoodsDTO> goodsDTOList = new ArrayList<>();
            records.forEach(f -> {
                GoodsDTO goodsDTO = DTOUtil.convertGoods(f);
                goodsDTOList.add(goodsDTO);
            });
            return goodsDTOList;
        } else {
            // 从数据库中查询用户发布的二手商品信息
            Page<Goods> page = new Page<>(pageIndex, pageSize);
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>().orderByDesc("goods_id");
            queryWrapper.eq("user_id", userId);
            page = goodsMapper.selectPage(page, queryWrapper);
            List<Goods> records = page.getRecords();
            List<GoodsDTO> goodsDTOList = new ArrayList<>();
            records.forEach(f -> {
                GoodsDTO goodsDTO = DTOUtil.convertGoods(f);
                goodsDTOList.add(goodsDTO);
            });

            // 将查询到的结果存入缓存中
            objectRedisTemplate.opsForHash().put("goods", cacheKey, JSONUtil.toJsonStr(records));
            return goodsDTOList;
        }
    }

    /**
     * 查询商品并排序，根据三种排序方式
     *
     * @param addressName  地址名称
     * @param price        价格排序方式
     * @param publishTime  发布时间排序方式
     * @return 排序后的商品信息列表
     */
//    @Cacheable(value = "goodsAddress", key = "#pageIndex")
    @Override
    public List<GoodsDTO> findAllGoodsByAddress(String addressName, String price, String publishTime, Integer pageIndex) {
        // 检查缓存中是否存在数据
//        String cacheKey = pageIndex.toString();
//        Boolean hasKey = objectRedisTemplate.opsForHash().hasKey("goodsAddress", cacheKey);
//
//        if (hasKey) {
//            // 从缓存中获取数据
//            List<Goods> goods = JSONObject.parseArray(objectRedisTemplate.opsForHash().get("goodsAddress", cacheKey).toString(), Goods.class);
//            List<GoodsDTO> goodsDTOList = new ArrayList<>();
//            goods.forEach(f -> {
//                GoodsDTO goodsDTO = DTOUtil.convertGoods(f);
//                UserDTO userInfoById = UserUtil.getUserDTOFromCache(f.getUserId(), objectRedisTemplate, userCenterFeignClient);
//                goodsDTO.setUserDTO(userInfoById);
//                goodsDTOList.add(goodsDTO);
//            });
//            return goodsDTOList;
//        } else {
            Page<Goods> page = new Page<>(pageIndex, pageSize);
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            if (price.equals("最高")) {
                queryWrapper.orderByDesc("goods_price");
            } else if (price.equals("最低")) {
                queryWrapper.orderByAsc("goods_price");
            }
            if (publishTime.equals("最新")) {
                queryWrapper.orderByDesc("create_time");
            } else if (publishTime.equals("最早")) {
                queryWrapper.orderByAsc("create_time");
            }
            if (!addressName.equals("不限园区")) {
                queryWrapper.like("address_name", addressName);
            }
            queryWrapper.eq("goods_status", 0).orderByDesc("goods_id");
            Page<Goods> selectPage = goodsMapper.selectPage(page, queryWrapper);
            List<Goods> goods = selectPage.getRecords();

            List<GoodsDTO> goodsDTOList = new ArrayList<>();
            goods.forEach(f -> {
                GoodsDTO goodsDTO = DTOUtil.convertGoods(f);
                UserDTO userInfoById = userCenterFeignClient.findUserInfoById(f.getUserId());
                goodsDTO.setUserDTO(userInfoById);
                goodsDTOList.add(goodsDTO);
            });

            // 将查询到的结果存入缓存中
//            objectRedisTemplate.opsForHash().put("goodsAddress", cacheKey, JSONUtil.toJsonStr(goods));
            return goodsDTOList;
//        }
    }

}
